<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <!-- 查询条件(分类) -->
    <el-card>
        <el-form :inline="true">
            <el-form-item label="一级分类">
                <el-select
                    v-model="category1"
                    placeholder="请选择一级分类"
                    size="middle"
                    style="width: 220px;margin-left: 10px;"
                    :disabled="addEditShow"
                    @change="handleCategory1Change"
                >
                    <el-option
                        v-for="item in categoryList1"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="二级分类">
                <el-select
                    v-model="category2"
                    placeholder="请选择二级分类"
                    size="middle"
                    style="width: 220px;margin-left: 10px;"
                    :disabled="addEditShow"
                    @change="handleCategory2Change"
                >
                    <el-option
                        v-for="item in categoryList2"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="三级分类">
                <el-select
                    v-model="category3"
                    placeholder="请选择三级分类"
                    size="middle"
                    style="width: 220px;margin-left: 10px;"
                    :disabled="addEditShow"
                    @change="handleCategory3Change"
                >
                    <el-option
                        v-for="item in categoryList3"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
    </el-card>
    <!-- 平台属性列表 -->
    <el-card style="margin-top: 10px;">
        <template v-if="!addEditShow">
            <div class="opeation">
                <el-button type="primary" icon="Plus" @click="addAttr" :disabled="!category3">添加平台属性</el-button>
            </div>
            <template v-if="tableData.length">
                <el-table :data="tableData" stripe="true" style="margin: 10px 0 20px;" border>
                    <el-table-column prop="id" label="序号" align="center" width="100"></el-table-column>
                    <el-table-column prop="attrName" label="属性名称" align="center" width="300"></el-table-column>
                    <el-table-column label="属性值名称" align="center">
                        <template #default="scope">
                            <el-tag v-for="item in scope.row?.attrValueList" :key="item.id" :type="`${item.id%2==0?'success':'warning'}`" style="margin: 0 5px;">{{ item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="" label="操作" align="center" width="300">
                        <template #default="scope">
                            <el-button type="warning" size="mini" icon="Edit" @click="editAttr(scope.row.id,scope.row.attrName)">编辑</el-button>
                            <el-popconfirm :title="`是否确认删除属性【${scope.row?.attrName||''}】?`" width="250px" icon="Delete" @confirm="confirmDelete(scope.row.id)">
                                <template #reference>
                                    <el-button type="danger" size="mini" icon="Delete">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <template v-else>
                <el-empty description="我辣么多的数据呢？！还不赶紧选择分类添加去~" />
            </template>
        </template>
        <template v-else>
            <div style="display: flex;align-items: center;">
                <label>属性名称</label>
                <el-input v-model="attrDto.attrName" placeholder="请输入属性名称" style="width: 200px;margin-left: 10px;"></el-input>
            </div>
            <div style="display: flex;margin-top: 20px;">
                <el-button type="primary" icon="Plus" @click="addAttrValue">添加属性值</el-button>
                <el-popconfirm title="是否确认清空属性值？" width="250px" icon="Delete" @confirm="clearAttrs">
                    <template #reference>
                        <el-button type="danger" icon="Delete" :disabled="!attrDto.attrValueList.length">清空属性值</el-button>
                    </template>
                </el-popconfirm>
            </div>
            <el-table :data="attrDto.attrValueList" stripe="true" style="margin: 10px 0 20px;" border>
                <el-table-column prop="id" label="序号" width="100"></el-table-column>
                <el-table-column label="属性值名称">
                    <template #default="scope">
                        <el-input :ref="(e:any) => inputArr[scope.$index] = e" v-if="scope.row.isEdit" v-model="scope.row.valueName" @blur="changeStatus(scope.$index,false)" placeholder="请输入属性值"></el-input>
                        <span v-else @click="changeStatus(scope.$index,true)">{{ scope.row.valueName }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="" label="操作">
                    <template #default="scope">
                        <el-popconfirm title="是否确认删除该属性值名称?" width="250px" icon="Delete" @confirm="deleteAttr(scope.$index)">
                            <template #reference>
                                <el-button type="danger" size="mini" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex;margin-top: 20px;">
                <el-button type="primary" icon="SuccessFilled" @click="saveAttrs">保存</el-button>
                <el-button type="default" icon="CircleCloseFilled" @click="handleClose">取消</el-button>
            </div>
        </template>
    </el-card>
</template>

<script lang="ts" setup>
    import { ref, reactive, onMounted, nextTick } from 'vue';
    import { ElMessage } from 'element-plus';
    import productApi from '@/api/product';

    // 查询条件/分类
    let category1 = ref('');
    let categoryList1 = ref([]);
    let category2 = ref('');
    let categoryList2 = ref([]);
    let category3 = ref('');
    let categoryList3 = ref([]);

    // 列表部分
    let tableData = ref([]);
    let addEditShow = ref(false);
    let attrDto = reactive({
        attrName: '',
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3
    });
    let inputArr = ref([]);

    const handleCategory1Change = async (val: number) => {
        category2.value = category3.value = '';
        categoryList2.value = categoryList3.value = tableData.value = [];
        const res = await productApi.getPropertyCategory2(val);
        if (res.code === 200) {
            categoryList2.value = res.data;
        } else ElMessage.error(res.message);
    };

    const handleCategory2Change = async (val: number) => {
        category3.value = '';
        categoryList3.value = tableData.value = [];
        const res = await productApi.getPropertyCategory3(val);
        if (res.code === 200) {
            categoryList3.value = res.data;
        } else ElMessage.error(res.message);
    };

    const handleCategory3Change = async () => {
        attrDto.categoryId = category3.value;
        const res = await productApi.getPropertyAttrList(category1.value, category2.value, category3.value);
        if (res.code === 200) {
            tableData.value = res.data;
        } else ElMessage.error(res.message);
    };

    const addAttr = () => {
        addEditShow.value = true;
    };

    const editAttr = async (id: number, attrName: string) => {
        addEditShow.value = true;
        let aDto = {
            id,
            attrName,
            attrValueList:[],
            categoryId: category3.value,
            categoryLevel: 3
        }
        const res = await productApi.getPropertyAttrById(id);
        if (res.code === 200) {
           aDto.attrValueList = res.data
           Object.assign(attrDto, JSON.parse(JSON.stringify(aDto)));
        } else ElMessage.error(res.message);
    }

    const confirmDelete = async (id: number) => {
        const res = await productApi.removePropertyAttrById(id);
        if (res.code === 200) {
            ElMessage.success('删除成功');
            handleCategory3Change();
        } else ElMessage.error(res.message);
    }

    const addAttrValue = () => {
        const id = (attrDto.attrValueList[attrDto.attrValueList.length-1]?.id || 0) + 1;
        attrDto.attrValueList.push({ id, valueName: '', isEdit: true });
        nextTick(()=>{
            inputArr.value[inputArr.value.length-1].focus();
        })
    }

    const changeStatus = (index: number, status: boolean) => {
        attrDto.attrValueList[index].isEdit = status;
        nextTick(()=>{
            if(status) inputArr.value[index].focus();
        })
    }


    const clearAttrs = () => {
        attrDto.attrValueList = [];
    }

    const deleteAttr = (index: number) => {
        attrDto.attrValueList.splice(index, 1);
    }

    const saveAttrs = async () => {
        if(!attrDto.attrName) return ElMessage.error('请输入属性名称');
        if(attrDto.attrValueList.length === 0) return ElMessage.error('请至少添加一条属性值');
        const res = await productApi.saveAttrInfo(attrDto);
        if (res.code === 200) {
            ElMessage.success(attrDto.id?'编辑成功':'保存成功');
            handleClose();
            handleCategory3Change();
        } else ElMessage.error(res.message);
    }
    
    const handleClose = () => {
        addEditShow.value = false;
        attrDto = reactive({
            attrName: '',
            attrValueList: [],
            categoryId: 0,
            categoryLevel: 3
        });
    }

    onMounted(async () => {
        const res = await productApi.getPropertyCategory1();
        if (res.code === 200) {
            categoryList1.value = res.data;
        } else ElMessage.error(res.message);
    })
</script>

<style scoped lang="scss">
    :deep(.el-form-item){
        margin-bottom: 0;
    }

    .categories{
        width: 100%;
        display: flex;
        .category_item{
            display: flex;
            align-items: center;
            margin-right: 30px;
        }
    }
</style>